package com.avecsys.quotemanager.service.security;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.security.MessageDigest;

import javax.mail.internet.MimeUtility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.avecsys.quotemanager.constants.ApplicationConstants;
import com.avecsys.quotemanager.utils.SystemConfig;

/**
 * 
 * @author Gurudath Reddy
 *
 */
public class CryptoServiceImpl implements CryptoService{

	private final Log log = LogFactory.getLog(LoginServiceImpl.class);
	
	/**
	 * This method provides client-side encryption of passwords. If <code>secure.passwords</code> are
	 * enabled in TurbineResources, the password will be encrypted, if not, it will be returned
	 * unchanged. The <code>secure.passwords.algorithm</code> property can be used to chose which digest
	 * algorithm should be used for performing the encryption. <code>SHA</code> is used by default.
	 *
	 * @param the password to process
	 * @return processed password
	 */
	public String encryptPassword(String password)
	{
		if (password == null)
		{
			return null;
		}
		String secure = SystemConfig.getProperty(ApplicationConstants.APPLICATION_SECURITY_PASSWORDS);
		String algorithm = SystemConfig.getProperty(ApplicationConstants.APPLICATION_SECURITY_PASSWORDS_ALGORITHM);
		if (secure.equals("true") || secure.equals("yes"))
		{
			try
			{
				MessageDigest md = MessageDigest.getInstance(algorithm);
				// We need to use unicode here, to be independent of platform's
				// default encoding. Thanks to SGawin for spotting this.
				byte[] digest = md.digest(password.getBytes("UTF-8"));
				ByteArrayOutputStream bas = new ByteArrayOutputStream(digest.length
						+ (digest.length
							/ 3)
							+ 1);
				OutputStream encodedStream = MimeUtility.encode(bas, "base64");
				encodedStream.write(digest);
				return bas.toString();
			}
			catch (Exception e)
			{
				log.debug("Password encryption failure : ",e);
				return null;
			}
		}
		else
		{
			return password;
		}
	}
}
